package com.briup.impl.server;

import com.briup.entity.Environment;
import com.briup.impl.util.ConnectionUtil;
import com.briup.inter.server.DBStore;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;


public class DBStoreImplBack implements DBStore {
    @Override
    public void saveDB(Collection<Environment> list) throws Exception {
        int count = 0;
        long start = System.currentTimeMillis();
        Connection conn = null;
        PreparedStatement ps = null;
        // 入库
        try {
            conn = ConnectionUtil.getConnection();
            conn.setAutoCommit(false); // 手动提交
            // env_detail_  变量 1
            String sql = "insert into environment" +
                    "(name, srcId, desId, devId, sersorAddress, count, cmd, data, status, gather_date) " +
                    "values(?,?,?,?,?,?,?,?,?,?)";
            // 预处理sql
            ps = conn.prepareStatement(sql);
            for (Environment e : list) {
                ps.setString(1, e.getName());
                ps.setString(2, e.getSrcId());
                ps.setString(3, e.getDesId());
                ps.setString(4, e.getDevId());
                ps.setString(5, e.getSersorAddress());
                ps.setInt(6, e.getCount());
                ps.setString(7, e.getCmd());
                ps.setFloat(8, e.getData());
                ps.setInt(9, e.getStatus());
                ps.setTimestamp(10,e.getGather_date());
                ps.addBatch();
                count++;
                if(count % 200 == 0){ // 每200 持久化一次
                    ps.executeBatch();
                    conn.commit();
                }
            }
            ps.executeBatch();
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {}
            e.printStackTrace();
        } finally {
            ConnectionUtil.close(conn,ps);
        }
        long end = System.currentTimeMillis();
        System.out.println("入库成功 时间为" + (end-start) + "毫秒");
    }
}
